package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 工程信息表Controller
 * 
 * @author SYGIS
 * @date 2023-09-13
 */
@RestController
@RequestMapping("/system/engineer")
public class SyEngineerController extends BaseController {

    @Autowired
    private ISyEngineerService syEngineerService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISyProjectService projectService;

    @Autowired
    private ISyFileInfoService fileInfoService;

    @Autowired
    private ISySubEngineerService subEngineerService;

    @Autowired
    private ISyDatasetInfoService datasetInfoService;

    @GetMapping("/getRoleEngineerList")
    public AjaxResult getRoleEngineerList(SyEngineer param) {
        List<SyEngineer> list = new ArrayList<>();
        List<SyEngineer> unbindRoleList = syEngineerService.selectUnbindRoleList(param.getRoleIds());
        List<SyEngineer> bindRoleList = syEngineerService.selectBindRoleList(param.getRoleIds());
        if(unbindRoleList.size()>0){
            for (SyEngineer res:unbindRoleList){
                res.setHasRole(0);
                list.add(res);
            }
        }
        if(bindRoleList.size()>0){
            for (SyEngineer res:bindRoleList){
                res.setHasRole(1);
                list.add(res);
            }
        }
        return AjaxResult.success(list);
    }

    @PostMapping("/saveRoleEngineer")
    public AjaxResult saveRoleEngineer(@RequestBody SyEngineer param){
        String[] ids = param.getIds().split(",");
        if(ids.length>0) {
            for (String id : ids) {
                SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(id);
                if(engineer!=null){
                    if(engineer.getRoleIds()!=null){
                        if(engineer.getRoleIds().indexOf(param.getRoleIds())<0){
                            engineer.setRoleIds(engineer.getRoleIds()+","+param.getRoleIds());
                        }
                    }else{
                        engineer.setRoleIds(param.getRoleIds());
                    }
                    syEngineerService.updateSyEngineer(engineer);
                }
            }
        }
        return AjaxResult.success();
    }

    @PostMapping("/unhookRoleEngineer")
    public AjaxResult unhookRoleEngineer(@RequestBody SyEngineer param) {
        SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(param.getUuid());
        if(engineer!=null){
            if(engineer.getRoleIds()!=null){
                String roleIds = engineer.getRoleIds().replaceAll(","+param.getRoleIds(),"").replaceAll(param.getRoleIds(),"");
                engineer.setRoleIds(roleIds);
                syEngineerService.updateSyEngineer(engineer);
            }
        }
        return AjaxResult.success();
    }

    @GetMapping("/getBindRoleEngineerList")
    public AjaxResult getBindRoleEngineerList(SyEngineer param) {
        List<SyEngineer> list = new ArrayList<>();
        List<SyEngineer> bindRoleList = syEngineerService.selectBindRoleList(param.getRoleIds());
        if(bindRoleList.size()>0){
            for (SyEngineer res:bindRoleList){
                res.setHasRole(1);
                list.add(res);
            }
        }
        return AjaxResult.success(list);
    }

    @GetMapping("/getEngineerList")
    public AjaxResult getEngineerList(){
        List<SyEngineer> list = syEngineerService.selectSyEngineerList4Select();
        return AjaxResult.success(list);
    }

    @GetMapping("/getEngineerList4Project")
    public AjaxResult getEngineerList4Project(SyEngineer syEngineer){
        List<SyEngineer> list = syEngineerService.getEngineerList4Project(syEngineer);
        if(list.size()>0){
            for(SyEngineer engineer:list){
                if(engineer.getProjectId()!=null){
                    engineer.setHasProject(1);
                }else{
                    engineer.setHasProject(0);
                }
            }
        }
        return AjaxResult.success(list);
    }

    @GetMapping("/getEngineerList4ProjectDetail")
    public AjaxResult getEngineerList4ProjectDetail(SyEngineer syEngineer){
        List<SyEngineer> list = syEngineerService.selectSyEngineerList(syEngineer);
        if(list.size()>0){
            for(SyEngineer engineer:list){
                if(engineer.getProjectId()!=null){
                    SyProject project = projectService.selectSyProjectByUuid(engineer.getProjectId());
                    if(project!=null){
                        engineer.setProjectName(project.getName());
                    }
                }
            }
        }
        return AjaxResult.success(list);
    }

    @PostMapping("/unhookEngineer")
    public AjaxResult unhookEngineer(@RequestBody SyEngineer syEngineer){
        syEngineerService.releaseEngineer(syEngineer.getUuid());
        return AjaxResult.success();
    }

    @GetMapping("/getProjectInfo4SubEngineer")
    public AjaxResult getProjectInfo4SubEngineer(SyEngineer syEngineer){
        SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(syEngineer.getUuid());
        Map<Object,Object> res = new HashMap<>();
        if(engineer!=null){
            if(engineer.getProjectId()!=null){
                SyProject project = projectService.selectSyProjectByUuid(engineer.getProjectId());
                if (project != null) {
                    res.put("projectId",project.getUuid());
                    res.put("projectName",project.getName());
                }else{
                    res.put("projectId",null);
                    res.put("projectName",null);
                }
            }else{
                res.put("projectId",null);
                res.put("projectName",null);
            }
        }else{
            res.put("projectId",null);
            res.put("projectName",null);
        }
        return AjaxResult.success(res);
    }

    @PostMapping("/createEngineerNo")
    public AjaxResult createEngineerNo(){
        SimpleDateFormat format = new SimpleDateFormat("YYYYMMddHHmmssSSS");
        String engineerNo = "YNJT-ENGINEER-"+format.format(new Date());
        Map<Object,Object> res = new HashMap<>();
        res.put("engineerNo",engineerNo);
        return AjaxResult.success(res);
    }

    @PostMapping("/editEngineer")
    public AjaxResult editEngineer(@RequestBody SyEngineer syEngineer) {
        if(syEngineer.getUuid()==null){ //新增
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            syEngineer.setUuid(uuid);
            syEngineer.setCreateBy(SecurityUtils.getLoginUser().getUserId().toString());
            syEngineer.setCreateTime(new Date());
            syEngineer.setStatus(1);
            syEngineerService.insertSyEngineer(syEngineer);
            // 给子工程挂接工程
            if(syEngineer.getSubEngineerIds()!=null){
                String[] subEngineerIds = syEngineer.getSubEngineerIds().split(",");
                if(subEngineerIds.length>0){
                    for(String subEngineerId:subEngineerIds){
                        SySubEngineer subEngineer = subEngineerService.selectSySubEngineerByUuid(subEngineerId);
                        if(subEngineer!=null){
                            subEngineer.setEngineerId(uuid);
                            if(syEngineer.getProjectId()!=null){
                                subEngineer.setProjectId(syEngineer.getProjectId());
                            }
                            subEngineerService.updateSySubEngineer(subEngineer);
                        }
                    }
                }
            }
        }else{ //修改
            syEngineer.setUpdateBy(SecurityUtils.getLoginUser().getUserId().toString());
            syEngineer.setUpdateTime(new Date());
            syEngineerService.updateSyEngineer(syEngineer);
            // 给子工程挂接工程
            if(syEngineer.getSubEngineerIds()!=null){
                String[] subEngineerIds = syEngineer.getSubEngineerIds().split(",");
                if(subEngineerIds.length>0){
                    for(String subEngineerId:subEngineerIds){
                        SySubEngineer subEngineer = subEngineerService.selectSySubEngineerByUuid(subEngineerId);
                        if(subEngineer!=null){
                            subEngineer.setEngineerId(syEngineer.getUuid());
                            if(syEngineer.getProjectId()!=null){
                                subEngineer.setProjectId(syEngineer.getProjectId());
                            }
                            subEngineerService.updateSySubEngineer(subEngineer);
                        }
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查询工程信息表列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SyEngineer syEngineer) {
        startPage();
        List<SyEngineer> list = syEngineerService.selectSyEngineerList(syEngineer);
        if(list.size()>0){
            for(SyEngineer engineer:list){
                if(engineer.getChargerId()!=null){
                    SysUser user = userService.selectUserById(engineer.getChargerId());
                    if(user!=null){
                        engineer.setChargerName(user.getNickName());
                    }
                }
                if(engineer.getDeptId()!=null){
                    SysDept dept = deptService.selectDeptById(engineer.getDeptId());
                    if(dept!=null){
                        engineer.setDeptName(dept.getDeptName());
                    }
                }
                if(engineer.getProjectId()!=null){
                    SyProject project = projectService.selectSyProjectByUuid(engineer.getProjectId());
                    if(project!=null){
                        engineer.setProjectName(project.getName());
                    }
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出工程信息表列表
     */
    @Log(title = "工程信息表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SyEngineer syEngineer) {
        List<SyEngineer> list = syEngineerService.selectSyEngineerList(syEngineer);
        ExcelUtil<SyEngineer> util = new ExcelUtil<SyEngineer>(SyEngineer.class);
        util.exportExcel(response, list, "工程信息表数据");
    }

    /**
     * 获取工程信息表详细信息
     */
    @GetMapping(value = "/{uuid}")
    public AjaxResult getInfo(@PathVariable("uuid") String uuid) {
        SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(uuid);
        if(engineer!=null){
            if(engineer.getMaterialAttach()!=null){
                List<SyFileInfo> attachList = getAttachList(engineer.getMaterialAttach());
                engineer.setAttachList(attachList);
            }
            if(engineer.getChargerId()!=null){
                SysUser user = userService.selectUserById(engineer.getChargerId());
                if(user!=null){
                    engineer.setChargerName(user.getNickName());
                }
            }
            if(engineer.getDeptId()!=null){
                SysDept dept = deptService.selectDeptById(engineer.getDeptId());
                if(dept!=null){
                    engineer.setDeptName(dept.getDeptName());
                }
            }
            if(engineer.getCreateBy()!=null){
                SysUser user = userService.selectUserById(Long.parseLong(engineer.getCreateBy()));
                if(user!=null){
                    engineer.setCreator(user.getNickName());
                }
            }
            if(engineer.getProjectId()!=null){
                SyProject project = projectService.selectSyProjectByUuid(engineer.getProjectId());
                if(project!=null){
                    engineer.setProjectName(project.getName());
                }
            }
        }
        return success(engineer);
    }

    public List<SyFileInfo> getAttachList(String attachUrl){
        String[] attachArray = null;
        if(attachUrl!=null){
            String url = attachUrl.replaceAll(" ","");
            if(url.length()>0){
                attachArray = attachUrl.split(",");
            }
        }
        List<SyFileInfo> list = new ArrayList<>();
        if(attachArray!=null){
            if(attachArray.length>0){
                for(String url:attachArray){
                    SyFileInfo fileInfo = new SyFileInfo();
                    fileInfo.setUrl(url);
                    List<SyFileInfo> files = fileInfoService.selectSyFileInfoList(fileInfo);
                    SyFileInfo file = files.get(0);
                    if(file!=null){
                        file.setName(file.getOriginName());
                    }
                    list.add(file);
                }
            }
        }
        return list;
    }

    /**
     * 新增工程信息表
     */
    @Log(title = "工程信息表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SyEngineer syEngineer) {
        return toAjax(syEngineerService.insertSyEngineer(syEngineer));
    }

    /**
     * 修改工程信息表
     */
    @Log(title = "工程信息表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SyEngineer syEngineer) {
        return toAjax(syEngineerService.updateSyEngineer(syEngineer));
    }

    /**
     * 删除工程信息表
     */
    @Log(title = "工程信息表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{uuids}")
    public AjaxResult remove(@PathVariable String[] uuids) {
        return toAjax(syEngineerService.deleteSyEngineerByUuids(uuids));
    }

    @PostMapping("/processStartEngineer")
    public AjaxResult processStartEngineer(@RequestBody SyEngineer syEngineer) {
        SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(syEngineer.getUuid());
        if(engineer!=null){
            engineer.setStatus(2);
            syEngineerService.updateSyEngineer(engineer);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的工程信息");
        }
    }

    @PostMapping("/processDeleteEngineer")
    public AjaxResult processDeleteEngineer(@RequestBody SyEngineer syEngineer) {
        SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(syEngineer.getUuid());
        if(engineer!=null){
            syEngineerService.deleteSyEngineerByUuid(engineer.getUuid());
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的工程信息");
        }
    }

    @PostMapping("/processRestartEngineer")
    public AjaxResult processRestartEngineer(@RequestBody SyEngineer syEngineer) {
        SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(syEngineer.getUuid());
        if(engineer!=null){
            engineer.setStatus(2);
            syEngineerService.updateSyEngineer(engineer);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的工程信息");
        }
    }

    @PostMapping("/processFinishEngineer")
    public AjaxResult processFinishEngineer(@RequestBody SyEngineer syEngineer) {
        SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(syEngineer.getUuid());
        if(engineer!=null){
            engineer.setStatus(3);
            syEngineerService.updateSyEngineer(engineer);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的工程信息");
        }
    }

    @PostMapping("/processNullifyEngineer")
    public AjaxResult processNullifyEngineer(@RequestBody SyEngineer syEngineer) {
        SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(syEngineer.getUuid());
        if(engineer!=null){
            engineer.setStatus(4);
            syEngineerService.updateSyEngineer(engineer);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的工程信息");
        }
    }

    @PostMapping("/processInitEngineer")
    public AjaxResult processInitEngineer(@RequestBody SyEngineer syEngineer) {
        SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(syEngineer.getUuid());
        if(engineer!=null){
            engineer.setStatus(1);
            syEngineerService.updateSyEngineer(engineer);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的工程信息");
        }
    }

    @GetMapping("/getDatasetEngineerList")
    public AjaxResult getDatasetEngineerList(SyEngineer param) {
        List<SyEngineer> list = syEngineerService.selectDatasetEngineerList();
        if(list.size()>0){
            for(SyEngineer engineer:list){
                List<SyDatasetInfo> datasets = datasetInfoService.selectDatasetByUuidAndEngineerId(param.getUuid(),engineer.getUuid());
                if(datasets.size()>0){
                    engineer.setHasRole(1);
                }else{
                    engineer.setHasRole(0);
                }
            }
        }
        return AjaxResult.success(list);
    }

    @PostMapping("/saveDatasetEngineer")
    public AjaxResult saveDatasetEngineer(@RequestBody SyEngineer param){
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        if(dataset!=null){
            if(dataset.getEngineerIds()!=null){
                String[] ids = param.getIds().split(",");
                if(ids.length>0) {
                    for (String id : ids) {
                        if(dataset.getEngineerIds().indexOf(id)<0){
                            dataset.setEngineerIds(dataset.getEngineerIds()+","+id);
                        }
                    }
                }
            }else{
                dataset.setEngineerIds(param.getIds());
            }
        }
        datasetInfoService.updateSyDatasetInfo(dataset);
        return AjaxResult.success();
    }

    @PostMapping("/unhookDatasetEngineer")
    public AjaxResult unhookDatasetEngineer(@RequestBody SyEngineer param){
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        if(dataset!=null){
            String engineerIds = dataset.getEngineerIds().replaceAll(","+param.getIds(),"").replaceAll(param.getIds(),"");
            dataset.setEngineerIds(engineerIds);
            datasetInfoService.updateSyDatasetInfo(dataset);
        }
        return AjaxResult.success();
    }

    @GetMapping("/getBindDatasetEngineerList")
    public AjaxResult getBindDatasetEngineerList(SyEngineer param) {
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        List<SyEngineer> list = new ArrayList<>();
        if(dataset!=null){
            if(dataset.getEngineerIds()!=null){
                if(dataset.getEngineerIds().length()>0){
                    String[] ids = dataset.getEngineerIds().split(",");
                    if(ids.length>0) {
                        for (String id : ids) {
                            if(id.replaceAll(" ","").length()>0){
                                SyEngineer engineer = syEngineerService.selectSyEngineerByUuid(id);
                                if(engineer!=null){
                                    engineer.setHasRole(1);
                                    list.add(engineer);
                                }
                            }
                        }
                    }
                }
            }
        }
        return AjaxResult.success(list);
    }
}
